package com.bootdo.acitvity.listener.message;


import com.bootdo.acitvity.listener.message.event.OrderFactory;
import com.bootdo.acitvity.listener.message.entity.PurchaseOrder;
import com.bootdo.acitvity.listener.message.entity.SalesOrder;
import com.bootdo.acitvity.listener.message.entity.TransportOrder;
import com.bootdo.acitvity.listener.message.event.component.EventComponent;
import com.bootdo.acitvity.listener.message.event.message.EventBus;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

@Data
public class OrderAggregateRoot {

    private String salesOrderId;
    private EventBus eventBus;
    private OrderFactory factory;

    private SalesOrder salesOrder;
    private Map<String, PurchaseOrder> purchaseOrders = new HashMap<>();
    private Map<String, TransportOrder> transportOrders = new HashMap<>();

    {
        eventBus = new EventBus();
        OrderFactory orderFactory = new OrderFactory(this);
        addBackendOrder(orderFactory);
    }

    public  OrderAggregateRoot addBackendOrder(EventComponent eventComponent){
        eventComponent.subscribe(eventBus);
        if (eventComponent instanceof OrderFactory) {
            factory = (OrderFactory) eventComponent;
        }
        if (eventComponent instanceof TransportOrder) {
            TransportOrder order = (TransportOrder) eventComponent;
            transportOrders.put(order.getOrderId(), order);
        }
        if (eventComponent instanceof PurchaseOrder) {
            PurchaseOrder order = (PurchaseOrder) eventComponent;
            purchaseOrders.put(order.getOrderId(), order);
        }
        if (eventComponent instanceof SalesOrder) {
            SalesOrder order = (SalesOrder) eventComponent;
            salesOrderId = order.getOrderId();
            salesOrder = order;
        }
        return this;
    }

    public void pushPurchaseOrder(String fsupplierOrderId) {
        PurchaseOrder purchaseOrder = purchaseOrders.get(fsupplierOrderId);
        purchaseOrder.createTransportOrder(this);
    }


}
